package com.itheima.controller;

import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author panweiwei
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    /**
     * 新增文章
     *
     * @param article
     * @return
     */
    @PostMapping
    public Result add(@RequestBody @Validated Article article) {
        articleService.add(article);
        return Result.success();
    }

    /**
     * 文章分页查询
     *
     * @param pageNum    页码
     * @param pageSize   总数
     * @param categoryId 分类id
     * @param state      状态
     * @return 返回分页
     */
    @GetMapping
    public Result<PageBean<Article>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state
    ) {
        PageBean<Article> pb = articleService.list(pageNum, pageSize, categoryId, state);
        System.out.println(pb);
        return Result.success(pb);
    }

    /**
     * 获取文章详情
     *
     * @param id 文章id
     * @return
     */
    @GetMapping("/detail")
    public Result<Article> detail(@RequestParam Integer id) {
        if (id == null) {
            return Result.error("参数不合法！");
        }
        Article article = articleService.findById(id);
        return Result.success(article);
    }

    /**
     * 更新文章
     *
     * @param article
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Article article) {
        articleService.update(article);
        return Result.success();
    }

    /**
     * 根据id删除文章
     * @param id 文章主键id
     * @return
     */
    @DeleteMapping
    public Result delete(@RequestParam Integer id) {
        if (id == null) {
            return Result.error("参数不符合要求");
        }
        articleService.deleteById(id);
        return Result.success();
    }
}
